package com.micro.shop.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.micro.shop.core.exception.AppException;
import com.micro.shop.enums.OrderStatusEnum;
import com.micro.shop.mapper.OrderMapper;
import com.micro.shop.mapper.OrderProductMapper;
import com.micro.shop.mapper.ProductBuyMapper;
import com.micro.shop.mapper.ProductMapper;
import com.micro.shop.mapper.ProductSkuMapper;
import com.micro.shop.model.Order;
import com.micro.shop.model.OrderCriteria;
import com.micro.shop.model.OrderProductWithBLOBs;
import com.micro.shop.model.OrderWithBLOBs;
import com.micro.shop.model.Product;
import com.micro.shop.model.ProductCriteria;
import com.micro.shop.model.ProductSku;
import com.micro.shop.model.ProductSkuCriteria;
import com.micro.shop.service.OrderService;
import com.micro.shop.utils.DateUtils;
import com.micro.shop.utils.OrderNumberUtil;
import com.micro.shop.vo.CreateOrderVO;
import com.micro.shop.vo.OrderListVO;
import com.micro.shop.vo.OrderProductVO;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	ProductMapper productMapper;
	
	@Autowired
	OrderProductMapper orderProductMapper;
	
	@Autowired
	ProductBuyMapper productBuyMapper;
	
	@Autowired
	ProductSkuMapper productSkuMapper;
	
	@Autowired
	OrderMapper orderMapper;
	
	@Override
	public void creatOrder(CreateOrderVO createOrderVO,Integer userId) {
		String goodsJsonStr = createOrderVO.getGoodsJsonStr();
		List<OrderProductVO> orderProductList=  JSON.parseObject(goodsJsonStr,new TypeReference<ArrayList<OrderProductVO>>() {});
		
		List<Integer> orderProductIdList = new ArrayList<Integer>();
		orderProductList.stream().forEach((orderProduct)->{
			orderProductIdList.add(orderProduct.getProductId());
		});
		
		ProductCriteria productCriteriaQuery = new ProductCriteria();
		productCriteriaQuery.createCriteria().andProductIdIn(orderProductIdList).andStatusEqualTo("1");
		Map<String,ProductSku> productSkuMap = new HashMap<String, ProductSku>();
		List<Product> productList = productMapper.selectByExample(productCriteriaQuery);
		Integer storeId = null;
		int index = 0;
		BigDecimal totalMoney = new BigDecimal(0);
		Integer totalBuyNumber = 0;
		for(Product product:productList){
			Integer buyNumber = 0;
			if(index == 0){
				storeId = product.getStoreId();
			}
			if(!storeId.equals(product.getStoreId()))	
				throw new AppException("暂时只支持单店铺提交订单");
			//购买数量
			for(OrderProductVO orderProductVO:orderProductList){
				if(product.getProductId().equals(orderProductVO.getProductId())){
					buyNumber+=orderProductVO.getNumber();
				}
			}
			totalBuyNumber+=buyNumber;
			// 限购
			if(product.getBuyerQuota()!=null && product.getBuyerQuota()>0){
				Integer buyCount = productBuyMapper.getProductPronum(product.getProductId(), userId);
				 if((buyNumber+buyCount)>product.getBuyerQuota()){
					 throw new AppException("对不起,"+product.getName()+"，您超出了限购");
				 }
			}
			//查库存
			BigDecimal productPrice = product.getPrice();
			if(product.getHasProperty()!=null && product.getHasProperty()==0){
				if(product.getQuantity()<buyNumber)
					throw new AppException("对不起,"+product.getName()+"，库存不足");
			}else{
				ProductSkuCriteria productSkuCriteriaQuery = new ProductSkuCriteria();
				List<ProductSku> productSkuList = productSkuMapper.selectByExample(productSkuCriteriaQuery);
				ProductSku productSku = productSkuList.get(0);
				productSkuMap.put(productSku.getProperties(), productSku);
				if(productSku.getQuantity()<buyNumber)
					throw new AppException("对不起,"+product.getName()+"，库存不足");
			}
			BigDecimal productMoney = productPrice.multiply(new BigDecimal(buyNumber));
			totalMoney = totalMoney.add(productMoney);
		}
		OrderWithBLOBs order = new OrderWithBLOBs();
		String order_no = OrderNumberUtil.makeOrderNum();
		order.setStoreId(storeId);
		order.setOrderNo(order_no);
		order.setTradeNo(order_no);
		order.setUid(userId);
		order.setProNum(totalBuyNumber);
		order.setProCount(totalBuyNumber);
		order.setSubTotal(totalMoney);
		Long nowTime = new Date().getTime()/1000;
		order.setAddTime(nowTime.intValue());
		order.setStatus(OrderStatusEnum.WAITING_PAY.getStatus());
		int orderId = orderMapper.insertSelective(order);
		
		for(OrderProductVO orderProductVO:orderProductList){
			OrderProductWithBLOBs orderProduct = new OrderProductWithBLOBs();
			orderProduct.setProductId(orderProductVO.getProductId());
			orderProduct.setOrderId(orderId);
			
			
		
		}
		
		
	}

	@Override
	public List<OrderListVO> orderList(Integer status, Integer userId) {
		List<OrderListVO>  orderList = new ArrayList<OrderListVO>();
		OrderCriteria orderCriteriaQuery = new OrderCriteria();
		orderCriteriaQuery.createCriteria()
		.andStatusEqualTo(status)
		.andUidEqualTo(userId);
		orderCriteriaQuery.setOrderByClause("add_time DESC");
		List<Order> orders = orderMapper.selectByExample(orderCriteriaQuery);
		if(CollectionUtils.isNotEmpty(orders)){
			orders.stream().forEach((order)->{
				OrderListVO orderListVO = new OrderListVO();
				BeanUtils.copyProperties(order, orderListVO);
				Date addTime = new Date(Long.valueOf(order.getAddTime()+"000"));
				orderListVO.setCreateTime(DateUtils.format(addTime, DateUtils.DAFAULT_DATETIME_FORMAT));
				orderList.add(orderListVO);
			});
		}
		 
		return orderList; 
	}

}
